console.log('test', require.main.filename);
const { readFileSync, writeFileSync } = require('fs');
const AsyncLock = require('async-lock');
// const path1 = '/ql/data/scripts/zxxb/function/'; // 生产
// const path1 = 'D:/code/fhs-vscode/gitee-pages-resources/ql/data/scripts/zxxb/function/'; // 公司
const path1 = 'D:/fhsy/dev/h5/gitee-pages-resources/ql/data/scripts/zxxb/function/'; // PC
// const path1 = 'D:/fhsy/dev/vscode/gitee-pages-resources/ql/data/scripts/zxxb/function/'; // 笔记本
let lock = new AsyncLock();

function set(key, value, filename) {
  // console.log('set调用者', (new Error()).stack.split("\n")[2].trim().split(" ")[1])
  lock.acquire(key, function(done) {
    // async work
    const data = get(null, filename) // 获取 All
    data[key] = value
    const dataString = JSON.stringify(data, null, 2)
    const path = `${path1}${filename}.json`
    writeFileSync(path, dataString)
    done();
  });
}
function get(key, filename) {
  // console.log('get调用者', (new Error()).stack.split("\n")[2].trim().split(" ")[1])
  const path = `${path1}${filename}.json`
  const sync = readFileSync(path).toString()
  if(!sync) {
    console.error('JSON 文件为空')
    return;
  }
  const storeData = JSON.parse(sync);
  if(key) {
    return storeData[key]
  }
  return storeData
}

module.exports = {
  set,
  get
}